package com.msh.automatic.android.api.controller.admin;

import com.alibaba.fastjson2.JSONObject;
import com.msh.automatic.android.api.util.JwksUtil;
import com.nimbusds.jose.*;
import com.nimbusds.jose.crypto.RSASSASigner;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;
import io.swagger.annotations.ApiOperation;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("/a/jwks")
public class JwksController {
    @Resource
    JwksUtil jwksUtil;
    @ApiOperation(value = "jwks的公钥")
    @RequestMapping(value = "pk.json",method = RequestMethod.GET)
    public Object pk() {
        JWKSet jwkSet = new JWKSet(jwksUtil.getKey().toPublicJWK());
        return jwkSet.toJSONObject();
    }

    @ApiOperation(value = "生成jwt")
    @RequestMapping(value = "jwt.json",method = RequestMethod.POST)
    public Object jwt(@RequestBody JSONObject params) throws JOSEException {

        // 构造声明（payload）
        JWTClaimsSet.Builder build = new JWTClaimsSet.Builder()
                .subject(params.getString("subject"))                    // 用户标识（sub）
                .issuer(params.getString("issuer"))                   // 签发者（iss）
                .audience(params.getString("audience"))                // 接收方（aud）
                .expirationTime(params.getDate("expirationTime"))             // 过期时间
                .issueTime(new Date());                             // 签发时间（iat）
        JSONObject claim = params.getJSONObject("claim");
        if(claim != null){
            for (String k: claim.keySet()){
                build = build.claim(k, claim.get(k));                 // 自定义字段
            }
        }
        // 使用 RSA 私钥进行签名
        JWSSigner signer = new RSASSASigner(jwksUtil.getKey().toPrivateKey());

        SignedJWT signedJWT = new SignedJWT(
                new JWSHeader.Builder(JWSAlgorithm.RS256)
                        .keyID(jwksUtil.getKey().getKeyID())
                        .type(JOSEObjectType.JWT)
                        .build(),
                build.build()
        );

        signedJWT.sign(signer);

        return signedJWT.serialize();
    }
}
